import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isEmpty from "lodash/isEmpty";
import _isUndefined from "lodash/isUndefined";
var _excluded = ["allowClear", "field", "label", "width", "inputSize", "className"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _class, _class2;

import React from 'react';
import { Icon, Input } from 'antd';
import { Bind } from 'lodash-decorators';
import { getCurrentLanguage, getResponse } from "../../../utils/utils";
import { queryTL } from "../../../services/api";
import TLModal from "./TLModal";
import "./index.less";
/**
 * 多语言组件 TLEditor
 *
 * @extends {Component} - React.PureComponent
 * @reactProps {!boolean} [allowClear=false] - 是否允许清除
 * @reactProps {!string} [field=''] - 表单域
 * @reactProps {!string} [label = ''] - 表单label
 * @reactProps {!string} [token = ''] - 数据加密token
 * @reactProps {!string} [width = '520px'] - 模态框宽度
 * @returns React.element
 * @example
 * import TLEditor from 'components/TLEditor';
 *
 *      <FormItem
 *      label={intl.get('cpfm.country.model.country.countryName').d('国家名称')}
 *      {...formLayout}
 *      >
 *        {getFieldDecorator('countryName', {
 *          initialValue: countryName,
 *          rules: [
 *            {
 *              type: 'string',
 *              required: true,
 *              message: intl.get('cpaas.common.validation.notNull', {
 *                name: intl.get('cpfm.country.model.country.countryName').d('国家名称'),
 *              }),
 *            },
 *          ],
 *        })(
 *          <TLEditor
 *            label={intl.get('cpfm.country.model.country.countryName').d('国家名称')}
 *            field="countryName"
 *            token={_token}
 *          />
 *        )}
 *      </FormItem>
 *
 */

var TLEditor = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), (_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(TLEditor, _React$Component);

  var _super = _createSuper(TLEditor);

  function TLEditor(props) {
    var _this;

    _classCallCheck(this, TLEditor);

    _this = _super.call(this, props);
    _this.state = {
      language: getCurrentLanguage() || 'zh_CN',
      // 获取系统当前语言
      loading: false,
      // 请求多语言列表loading
      modalVisible: false,
      // 控制多语言模态框
      list: [],
      // 多语言列表
      resLangList: [],
      // 接口返回的多语言数据
      text: props.value,
      // 输入框显示值
      isSave: false
    };
    return _this;
  }

  _createClass(TLEditor, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      // 初始化时清空表单多语言字段
      this.props.form.setFieldsValue({
        _tls: null
      });
    } // eslint-disable-next-line

  }, {
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      var text = this.state.text;

      if (text && text !== nextProps.value) {
        this.setState({
          text: nextProps.value
        });
      }

      if (!text && nextProps.value) {
        this.setState({
          text: nextProps.value
        });
      }
    }
  }, {
    key: "showLoading",
    value: function showLoading(flag) {
      this.setState({
        loading: flag
      });
    }
  }, {
    key: "onCancel",
    value: function onCancel() {
      var _this$props$form = this.props.form,
          form = _this$props$form === void 0 ? {} : _this$props$form;

      if (form && !_isUndefined(form.getFieldValue('_tls'))) {
        form.resetFields(['_tls']);
      }

      this.setState({
        modalVisible: false,
        isSave: false
      });
    }
  }, {
    key: "save",
    value: function save(data) {
      var _this$props = this.props,
          form = _this$props.form,
          fieldName = _this$props.field;
      var _this$state = this.state,
          list = _this$state.list,
          language = _this$state.language; // 设置多语言后，构建编辑的数据结构

      var newList = Object.keys(data).map(function (item) {
        var filterName = list.find(function (items) {
          return item === items.code;
        });
        return {
          code: item,
          value: data[item],
          name: filterName.name || ''
        };
      });
      this.setState({
        text: data[language],
        list: newList,
        modalVisible: false,
        isSave: true
      });

      if (form && _isUndefined(form.getFieldValue('_tls'))) {// 往外层form配置_tls表单域
        // form.registerField('_tls');
        // 设置_tls值
        // form.setFieldsValue({ _tls: { [fieldName]: data } });
      } else {
        var oldTls = form.getFieldValue('_tls');

        var newTls = _objectSpread(_objectSpread({}, oldTls), {}, _defineProperty({}, fieldName, data));

        form.setFieldsValue({
          _tls: newTls
        });
      } // 更新input显示值


      if (this.props.onChange) {
        this.props.onChange(data[language]);
      }
    }
  }, {
    key: "openModal",
    value: function openModal() {
      var _this2 = this;

      var _this$props2 = this.props,
          data = _this$props2.data,
          _this$props2$field = _this$props2.field,
          fieldName = _this$props2$field === void 0 ? '' : _this$props2$field,
          _this$props2$token = _this$props2.token,
          _token = _this$props2$token === void 0 ? '' : _this$props2$token;

      var _this$state2 = this.state,
          list = _this$state2.list,
          text = _this$state2.text,
          language = _this$state2.language;
      var _this$state$resLangLi = this.state.resLangList,
          resLangList = _this$state$resLangLi === void 0 ? [] : _this$state$resLangLi;

      if (Array.isArray(resLangList) && resLangList.length === 0 && _isEmpty(data)) {
        // 仅调用一次接口，后续更新都使用缓存的语言数据
        queryTL({
          fieldName: fieldName,
          _token: _token
        }).then(function (res) {
          if (getResponse(res)) {
            _this2.setState({
              resLangList: res
            });

            _this2.setCacheList(res, list, language, text);
          }
        });
      } else {
        if (!_isEmpty(data) && data[fieldName]) {
          resLangList = Object.keys(data[fieldName]).map(function (key) {
            var name = '';

            if (key === 'zh_CN') {
              name = '简体中文';
            } else if (key === 'en_US') {
              name = 'English';
            } else {
              name = '日本語';
            }

            return {
              name: name,
              code: key,
              value: data[fieldName][key]
            };
          });
        }

        this.setCacheList(resLangList, list, language, text);
      }
    }
  }, {
    key: "setCacheList",
    value: function setCacheList(resLangList, list, language, text) {
      var newRes = resLangList.map(function (item, index) {
        var obj = _objectSpread({}, item);

        if (Array.isArray(list) && list[index] !== undefined) {
          // 处理修改后值的回显
          if (list[index].value) {
            obj.value = list[index].value;
          }
        } // 处理编辑外部输入框之后


        if (language === item.code) {
          obj.value = text;
        }

        return obj;
      });
      this.setState({
        modalVisible: true,
        list: newRes
      });
    }
  }, {
    key: "onChange",
    value: function onChange(e) {
      var isSave = this.state.isSave;
      this.setState({
        text: e.target.value
      });

      if (this.props.onChange) {
        this.props.onChange(e.target.value); // 未保存的多语言数据，清空_tls字段，清除缓存

        if (!isSave) {
          this.props.form.setFieldsValue({
            _tls: null
          });
        }
      }
    }
  }, {
    key: "emitEmpty",
    value: function emitEmpty() {
      var _this3 = this;

      if (this.props.onChange) {
        this.setState({
          text: null
        }, function () {
          _this3.props.onChange(null);
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props3 = this.props,
          _this$props3$allowCle = _this$props3.allowClear,
          allowClear = _this$props3$allowCle === void 0 ? false : _this$props3$allowCle,
          fieldName = _this$props3.field,
          _this$props3$label = _this$props3.label,
          label = _this$props3$label === void 0 ? '' : _this$props3$label,
          width = _this$props3.width,
          _this$props3$inputSiz = _this$props3.inputSize,
          inputSize = _this$props3$inputSiz === void 0 ? {} : _this$props3$inputSiz,
          _this$props3$classNam = _this$props3.className,
          className = _this$props3$classNam === void 0 ? '' : _this$props3$classNam,
          otherProps = _objectWithoutProperties(_this$props3, _excluded);

      var _this$props$disabled = this.props.disabled,
          disabled = _this$props$disabled === void 0 ? false : _this$props$disabled;
      var _this$state3 = this.state,
          text = _this$state3.text,
          modalVisible = _this$state3.modalVisible,
          list = _this$state3.list,
          loading = _this$state3.loading;
      var modalProps = {
        label: label,
        fieldName: fieldName,
        modalVisible: modalVisible,
        list: list,
        width: width,
        inputSize: inputSize,
        onCancel: this.onCancel,
        onOK: this.save
      };
      var classNames = [className, 'tl-editor']; // eslint-disable-next-line no-unused-vars

      var suffix = /*#__PURE__*/React.createElement(React.Fragment, null, allowClear && text && /*#__PURE__*/React.createElement(Icon, {
        type: "close-circle",
        onClick: this.emitEmpty,
        className: "tl-editor-clear"
      }), /*#__PURE__*/React.createElement(Icon, {
        type: loading ? 'loading' : 'global',
        className: "tl-editor-trigger" // eslint-disable-next-line no-nested-ternary
        ,
        style: loading ? {} : disabled ? {
          cursor: 'not-allowed'
        } : {
          cursor: 'pointer'
        },
        onClick: !loading && !disabled ? this.openModal : undefined
      }));
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Input, Object.assign({}, otherProps, {
        onChange: this.onChange,
        value: text,
        className: classNames.join(' ') // suffix={suffix}

      })), /*#__PURE__*/React.createElement(TLModal, modalProps));
    }
  }]);

  return TLEditor;
}(React.Component), _class2.displayName = 'TLEditor', _class2), (_applyDecoratedDescriptor(_class.prototype, "showLoading", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "showLoading"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onCancel", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "onCancel"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "save", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "save"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "openModal", [_dec4], Object.getOwnPropertyDescriptor(_class.prototype, "openModal"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "setCacheList", [_dec5], Object.getOwnPropertyDescriptor(_class.prototype, "setCacheList"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onChange", [_dec6], Object.getOwnPropertyDescriptor(_class.prototype, "onChange"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "emitEmpty", [_dec7], Object.getOwnPropertyDescriptor(_class.prototype, "emitEmpty"), _class.prototype)), _class));
export { TLEditor as default };